import os
import sys
import logging
from sqlalchemy import create_engine, inspect
from sqlalchemy.orm import sessionmaker
import random
from datetime import datetime, timedelta
import time
import sqlite3

# 添加项目根目录到系统路径
sys.path.append(os.path.dirname(os.path.abspath(__file__)))

# 导入 Base 和引擎
from app.core.database import Base, engine

# 导入模型
from app.models.models import User, Device
from app.core.security import get_password_hash

# 配置日志
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)


def create_tables():
    """创建所有数据库表"""
    try:
        # 清理现有连接
        engine.dispose()

        # 显式创建表
        Base.metadata.create_all(bind=engine)
        logger.info("数据库表已创建")

        # 验证表是否创建成功
        inspector = inspect(engine)
        table_names = inspector.get_table_names()
        logger.info(f"已创建的表: {table_names}")

        if "users" not in table_names:
            logger.warning("users 表未创建，尝试单独创建")
            User.__table__.create(bind=engine)
            logger.info("users 表已创建")

        if "devices" not in table_names:
            logger.warning("devices 表未创建，尝试单独创建")
            Device.__table__.create(bind=engine)
            logger.info("devices 表已创建")

        return True
    except Exception as e:
        logger.error(f"创建数据库表失败: {e}")
        return False


def create_admin_user(db):
    """创建默认管理员用户"""
    try:
        admin_user = db.query(User).filter(User.username == "admin").first()
        if not admin_user:
            # 只使用模型中存在的字段
            admin_user = User(
                username="admin",
                nickname="小东",
                hashed_password=get_password_hash("admin123"),
                avatar="https://avatars.githubusercontent.com/u/44761321",
                roles="admin",
                permissions="*:*:*",
                is_active=True
            )
            db.add(admin_user)
            db.commit()
            logger.info("创建默认管理员用户成功")
        else:
            logger.info("管理员用户已存在")
        return True
    except Exception as e:
        logger.error(f"创建管理员用户失败: {e}")
        db.rollback()
        return False


def initialize_device_data(db):
    """初始化设备数据"""
    try:
        # 检查是否已有数据
        if db.query(Device).count() > 0:
            logger.info("数据库已有设备数据，跳过初始化")
            return True

        logger.info("开始初始化设备数据")

        online_statuses = ["online", "offline"]
        versions = ["v1.0.0", "v1.1.0", "v1.2.0", "v2.0.0", "v2.1.0"]

        # 使用集合跟踪已生成的设备ID
        generated_dev_ids = set()

        for i in range(100):
            while True:
                dev_id = f"DEV-{random.randint(1000, 9999)}"
                # 确保设备ID唯一（在本次初始化中）
                if dev_id not in generated_dev_ids:
                    # 检查数据库中是否已存在（虽然数据库为空，但为了健壮性）
                    if not db.query(Device).filter(Device.dev_id == dev_id).first():
                        generated_dev_ids.add(dev_id)
                        break

            device = Device(
                dev_id=dev_id,
                cpu_ser=f"CPU-{random.randint(10000000, 99999999)}",
                # emmc_ser=f"EMMC-{random.randint(10000000, 99999999)}",
                mac_add=":".join(f"{random.randint(0, 255):02x}" for _ in range(6)),
                activated_time=(datetime.now() - timedelta(days=random.randint(0, 30))).strftime(
                    "%Y-%m-%d %H:%M:%S"),
                cpu_usage=random.randint(0, 100),
                mem_usage=random.randint(0, 100),
                # emmc_usage=random.randint(0, 100),
                # ip_address=f"192.168.{random.randint(0, 255)}.{random.randint(0, 255)}",
                firmware_version=random.choice(versions),
                app_version=random.choice(versions),
                online_status=random.choice(online_statuses),
                brightness=random.randint(0, 100) if random.random() > 0.3 else None,
                volume=random.randint(0, 100) if random.random() > 0.3 else None,
                last_active=time.time() - random.randint(0, 86400)  # 1天内随机时间
            )
            db.add(device)

        db.commit()
        logger.info(f"成功初始化 {db.query(Device).count()} 条设备数据")
        return True
    except Exception as e:
        logger.error(f"初始化设备数据失败: {str(e)}")
        db.rollback()
        return False


def main():
    """主初始化函数"""
    # 创建数据库表
    if not create_tables():
        logger.error("数据库初始化失败，无法继续")
        return

    # 创建会话
    SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
    db = SessionLocal()

    try:
        # 创建管理员用户
        if not create_admin_user(db):
            logger.error("管理员用户创建失败")
            return

        # 初始化设备数据
        if not initialize_device_data(db):
            logger.error("设备数据初始化失败")
            return

        logger.info("数据库初始化完成")
    except Exception as e:
        logger.error(f"数据库初始化过程中发生错误: {e}")
    finally:
        db.close()


if __name__ == "__main__":
    main()